/*
Auteur        :Valentijn Polder
Studentnummer :0782531

$Log$

*/
#include <stdlib.h>
#include <mod/include/PIT.h>
#include <mod/include/LM92.h>
//#define RAND_MAX 100

unsigned int started=0,random=50;

void PIT_Start(void){
//   p_pPITC->PITC_PIMR = 0x03002710;
   p_pPITC->PITC_PIMR = 0x030434F0;
//   p_pPITC->PITC_PIMR = 0x03006BB2;
   if(!started){
      LM92_Init();
      AT91C_BASE_AIC->AIC_IDCR = 0x00000046;
      AT91C_BASE_AIC->AIC_SVR[1] = (unsigned int) &PIT_Interrupt;
      AT91C_BASE_AIC->AIC_SMR[1] = 0x00000026;
      AT91C_BASE_AIC->AIC_ISCR = 0x00000046;
      AT91C_BASE_AIC->AIC_ICCR = 0x00000002;
      AT91C_BASE_AIC->AIC_IECR = 0x00000046;
      p_pPIO->PIO_OER=0x100;
      started=1;
   }
}

void PIT_Stop(void){
   p_pPITC->PITC_PIMR = 0x00000000;
   p_pPIO->PIO_ODR=0x100;
   started=0;
}

void PIT_Interrupt(void){
   volatile int status;
   static unsigned int i,cnt;
   unsigned char str[5]={'0','0','0','\n','\n'};
   if(started){
      status = AT91C_BASE_PITC->PITC_PIVR;
//   UART0_Write(i+48);
      if(i%2){
         p_pPIO->PIO_SODR=0x100;
      }else{
         p_pPIO->PIO_CODR=0x100;
      }
      if(random<=cnt){
         if(random==0){
//            p_pPIO->PIO_CODR=0x08000000;
         }
//         p_pPIO->PIO_SODR=0x08000000;
      }else{
//         p_pPIO->PIO_CODR=0x08000000;
      }
      if(cnt<10){
         cnt++;
      }else{
         status=LM92_Read();
         UART0_Write(0x0F);
         UART0_Write(status>>8);
         UART0_Write(status);
//      UART0_Write('\n');
         cnt=0;
         i++;
         srand(rand());
         random=rand();
         random= random/327;
/*         str[0]=random/100;
         random-=str[0]*100;
         str[1]=random/10;
         random-=str[1]*10;
         str[2]=random;
         random+=str[1]*10;
         random+=str[0]*100;
         str[2]+=48;
         str[1]+=48;
         str[0]+=48;
         LCD_Writeln(&str);*/
         UART0_Write(0xF0);
         UART0_Write(random);
      }
   }
}



// pit clock = mck/16
// 2DC6C0
